# Author: Chris Moyer
# JanRain Authentication version of the AuthHandlers
import re
import sys
import os, os.path

import urllib, urllib2

import marajo
from marajo.appengine.handlers import RequestHandler
from marajo.appengine.ext.webapp import status, template
from marajo.appengine.api.users import User
from boto.exception import SDBResponseError

try:
	import json
except:
	import simplejson as json

import logging
log = logging.getLogger("marajo.handlers.auth.janrain")

import marajo.appengine.handlers.auth

marajo.config['handlers'].append( { "url": "/_ah/login", "handler": "marajo.appengine.handlers.auth.janrain.LoginHandler" })

class LoginHandler(RequestHandler):
	"""JanRain based login handler. See:
	http://rpxnow.com for more details"""

	def get(self):
		"""If they're sending us a GET request, we redirect them to the 
		janrain login URL"""
		return self.redirect("%s?token_url=/_ah/login" % marajo.config.get("janrain", "url"))

	def post(self):
		"""JanRain login handler"""
		from marajo.appengine.api.users.janrain import User as JanRainUser
		janrain_token = self.request.POST.get("token")
		jr_user = JanRainUser(janrain_token)
		auth_domain = marajo.config.get("auth_domain")
		if auth_domain:
			import boto
			sdb = boto.connect_sdb()
			try:
				User._manager.domain = sdb.get_domain(auth_domain)
			except SDBResponseError:
				User._manager.domain = sdb.create_domain(auth_domain)
		try:
			user = User.find(oids=jr_user.id).next()
			self.session['user'] = user.id
		except:
			log.error("Unknown OID: %s" % jr_user.id)
		return self.redirect("/")
